#!/bin/sh /etc/rc.common
# Copyright (C) 2020 OpenWrt.org

START=99
BIN=/usr/sbin/forked-daapd
PID=/var/run/forked-daapd.pid
SSD=start-stop-daemon

NAME=forked-daapd

uci_get_by_name() {
	local ret=$(uci get $NAME.$1.$2 2>/dev/null)
	echo ${ret:=$3}
}

uci_get_by_type() {
	local ret=$(uci get $NAME.@$1[0].$2 2>/dev/null)
	echo ${ret:=$3}
}

gen_config_file() {
cat <<-EOF >/var/etc/forked-daapd.conf
general {
	uid = "root"
	db_path = "$(uci_get_by_type forked-daapd db_path)"
	logfile = "/var/log/forked-daapd.log"
	loglevel = log
	ipv6 = no
	cache_path = "/var/forked-daapd-cache.db"
}

library {
	name = "My Music on OpenWrt"
	port = $(uci_get_by_type forked-daapd port 3689)
	directories = { "$(uci_get_by_type forked-daapd directories)" }
	podcasts = { "/Podcasts" }
	audiobooks = { "/Audiobooks" }
	compilations = { "/Compilations" }
	compilation_artist = "Various Artists"
}

audio {
	nickname = "Local Audio Output"
	type = "alsa"
}
EOF
}

start() {
        gen_config_file
        local enabled=$(uci_get_by_type forked-daapd enabled 0)
        [ "$enabled" == "0" ] && return 1
        $SSD -p $PID -S -x $BIN -- -P $PID -c /var/etc/forked-daapd.conf
}
	
stop() {
        $SSD -p $PID -K -s SIGINT >/dev/null
}

restart() {
        stop
        sleep 3
        start
}
